<template>
    <div class='space-y-2'>
        <div v-for="(item, index) in list" class='flex items-center space-x-1' :key="index">
          <Input
            :readOnly="readonly"
            :value="item.variable"
            @hange="handleVarNameChange(index)"
            wrapperClassName='grow'
          />
          <VarTypePicker
            :readonly="readonly"
            :value="item.variable_type"
            @change="handleVarTypeChange(index)"
          />
          <Button
            class='!bg-gray-100 !p-2 hover:!bg-gray-200'
            @click="handleVarRemove(index)"
          ><PlusOutlined/></Button>
        </div>
    </div>
</template>
<script setup lang="ts" name="OutputVarList">
import {ref,computed} from 'vue';
import { Input ,Button, message} from 'ant-design-vue';
import { PlusOutlined } from '@ant-design/icons-vue';

import type { OutputVar } from '../../../code/types'
import VarTypePicker from './var-type-picker'
import type { VarType } from '@/app/components/workflow/types'
import { checkKeys } from '@/utils/var'
import { ChangeEvent } from 'ant-design-vue/es/_util/EventInterface';

type Props = {
  readonly: boolean
  outputs: OutputVar
  outputKeyOrders: string[]
  onChange: (payload: OutputVar, changedIndex?: number, newKey?: string) => void
  onRemove: (index: number) => void
}

const props = defineProps<Props>();


const list = computed(()=> {
  return props.outputKeyOrders.map((key) => {
  return {
    variable: key,
    variable_type: props.outputs[key]?.type,
  }
 }) 
})
  const handleVarNameChange = (index: number) => {
    return (e: ChangeEvent) => {
      const oldKey = list.value[index].variable;
      const newKey = e.target.value

      const { isValid, errorKey, errorMessageKey } = checkKeys([newKey], true)
      if (!isValid) {
        message.error(`appDebug.varKeyError.${errorMessageKey}: ${errorKey}`)
        return
      }

      if (list.value.map(item => item.variable?.trim()).includes(newKey.trim())) {
        message.error(`${newKey} 已存在`)
        return
      }
      const newOutputs = {...props.outputs};
      newOutputs[newKey!] = newOutputs[oldKey];
      delete newOutputs[oldKey]
      props.onChange(newOutputs, index, newKey)
    }
  }

  const handleVarTypeChange = (index: number) => {
    return (value: string) => {
      const key = list.value[index].variable;
      const newOutputs = {...props.outputs};
      newOutputs[key].type = value as VarType
      props.onChange(newOutputs)
    }
  }

  const handleVarRemove = (index: number) => {
    return () => {
      props.onRemove(index)
    }
  }

</script>

